<template>
  <div :id="'map-container' + random" class="map-container"></div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'

export default {
  data() {
    return {
      random: 0,
      keywordRandom: 0,
      keyword: null,
      map: null,
      marker: null
    }
  },
  created() {
    this.random = Math.ceil(Math.random() * 1000)
    this.keywordRandom = Math.ceil(Math.random() * 1000)
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      this.initMap()
    },
    initMap() {
      var _this = this
      AMapLoader.load({
        key: '7bf1afe0a111e75bc96b5f5d0553b5f3', // 申请好的Web端开发者Key，首次调用 load 时必填
        version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['AMap.Geolocation'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        AMapUI: {
          version: '1.1',
          plugins: ['overlay/SimpleMarker']
        }
      })
        .then(AMap => {
          // console.log(AMapUI, 'AMapUI')
          _this.map = new AMap.Map('map-container' + this.random, {
            //设置地图容器id
            // resizeEnable: true,
            viewMode: '3D', //是否为3D地图模式
            zoom: 16, //设置地图的缩放级别
            center: [119.646354, 29.129608], //初始化地图中心点位置
            mapStyle: 'amap://styles/macaron', // 设置地图的显示样式
            touchZoomCenter: true
          })

          const marker = new AMap.Marker({
            position: _this.map.getCenter(),
            icon: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
            offset: new AMap.Pixel(-13, -30),
            // 设置是否可以拖拽
            draggable: true,
            cursor: 'move'
          })
          marker.on('dragend', function(e) {
            const position = this.getPosition()
            _this.$emit('getCenter', [position.lng, position.lat])
          })
          marker.setMap(_this.map)
          this.marker = marker

          //输入提示
          // var auto = new AMap.AutoComplete({
          //   input: "tipinput" + this.keywordRandom
          // });

          // _this.map.on('dragend', function (e){
          //   const position = this.getCenter()
          //   _this.$emit('getCenter', [position.lng, position.lat])
          // })
        })
        .catch(e => {
          console.log(e)
        })
    },
    setPosition(position) {
      // 设定地图中心点 和 marker位置
      const pos = position.map(x => x - 0)

      this.map.setCenter(position)

      this.marker.setPosition(position)
    }
  }
}
</script>
<style scoped>
.map-container {
  width: 100%;
  height: 100%;
}
</style>
